package com.gzhryc.shared_device.common.payment.services;

import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.common.payment.dao.WXPayConfigDao;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayConfig;
import com.gzhryc.shared_device.common.payment.dao.enums.EAppType;
import com.gzhryc.shared_device.common.payment.dao.enums.WXPayConfigEnum;
import com.gzhryc.shared_device.common.payment.services.dto.WXPayConfigSearch;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class WXPayConfigService {

    static Logger log = Logger.getLogger(WXPayConfigService.class);

    public static WXPayConfigService self() {
        return MultiDBTools.getService(WXPayConfigService.class, true);
    }

    public static WXPayConfigService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, WXPayConfigService.class, true);
    }

    WXPayConfigDao dao;

    public WXPayConfigService(String jdbcKey) {
        this.dao = new WXPayConfigDao(jdbcKey);
    }

    public List<WXPayConfig> findAll(){
        try {
            return dao.findAll();
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<WXPayConfig> findByAppType(Integer appType){
        if(appType != null) {
            Conditions conditions = new Conditions(WXPayConfig.class);
            conditions.and().is("appType", appType);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public List<WXPayConfig> findJoinBySearch(WXPayConfigSearch search, Integer pageNo, Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.desc("createDate");
        try {
            return dao.findJoinByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countJoinBySearch(WXPayConfigSearch search){
        Conditions conditions = dao.buildConditions(search);
        try {
            return dao.countJoin(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public Long countByAccountGroupId(Long accountGroupId){
        if(accountGroupId != null){
            Conditions conditions = new Conditions(WXPayConfig.class);
            conditions.and().is("accountGroupId",accountGroupId);

            try {
                return dao.count(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return 0L;
    }

    public WXPayConfig getByAppId(String appId){
        try {
            return dao.getById(appId);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }
    
    public WXPayConfig getJoinByAppId(String appId){
        try {
            return dao.getJoinById(appId);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }
    
    public WXPayConfig getDef(Integer appType){
    	if(appType != null) {
	    	Conditions conditions = new Conditions(WXPayConfig.class);
	    	conditions.and().is("appType", appType);
	        conditions.and().is("state",WXPayConfigEnum.State.Default.index());
	        
	        try {
	            return dao.get(conditions);
	        } catch (SQLException e) {
	            log.error(e.getMessage(),e);
	        }
    	}
        return null;
    }

    public boolean add(WXPayConfig wxPayConfig) throws LogicException {
        WXPayConfig defConfig = getDef(wxPayConfig.getAppType());
        if(defConfig == null) {
        	wxPayConfig.setState(WXPayConfigEnum.State.Default.index());
        }else if(wxPayConfig.getState() != null && WXPayConfigEnum.State.Default.index().equals(wxPayConfig.getState())){
        	throw new LogicException("已存在默认的配置");
        }
        
        wxPayConfig.setCreateDate(new Date());
        
        try {
            return dao.insert(wxPayConfig) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean updateNotNull(WXPayConfig wxPayConfig) throws LogicException{
    	WXPayConfig defConfig = null;
    	if(wxPayConfig.getState() != null) {
    		if(WXPayConfigEnum.State.Default.index().equals(wxPayConfig.getState())) {
    			defConfig = getDef(wxPayConfig.getAppType());
    			if(defConfig!= null && defConfig.getAppId().equals(wxPayConfig.getAppId())){
    				defConfig = null;
    			}
    		}
    	}else {
    		defConfig = getDef(wxPayConfig.getAppType());
    		if(defConfig == null) {
    			wxPayConfig.setState(WXPayConfigEnum.State.Default.index());
    		}else {
    			defConfig = null;
    			wxPayConfig.setState(WXPayConfigEnum.State.Normal.index());
    		}
    			
    	}
    	
    	JdbcSession.begin();
    	try {
            if(dao.updateNotNull(wxPayConfig) > 0){
            	if(defConfig != null) {
            		Conditions condition = new Conditions(WXPayConfig.class);
            		condition.and().is("appId", defConfig.getAppId());
            		
            		WXPayConfig updateEntity = new WXPayConfig();
            		updateEntity.setState(WXPayConfigEnum.State.Normal.index());
            		
            		if(dao.updateNotNull(updateEntity, condition) > 0) {
            			JdbcSession.commit();
            			return true;
            		}
            	}else {
            		JdbcSession.commit();
            		return true;
            	}
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        } finally {
        	JdbcSession.end();
        }
    	
        return false;
    }

    public boolean deleteByAppId(String appId) throws LogicException{
        JdbcSession.begin();
        try {
            if(dao.deleteById(appId) > 0){
                if(AppConfigService.self().deleteByKeys(appId, EAppType.Weixin.index())){
                    JdbcSession.commit();
                    return true;
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }finally {
            JdbcSession.end();
        }
        return false;
    }
}
